import { defineComponent, ref, reactive, onMounted, onUnmounted } from "vue";
import TablePage from "@/components/TablePage/TablePage";
import { tablesInterface } from "@/common/interface/table.interface";
import SongFileService from "./index.service";
import styles from "./index.module.less";
import Add from "./Add/Add";
import to from "await-to-js";
export default defineComponent({
  name: "FileList",
  setup() {
    const tablePageRef = ref(null as any);
    const songFileService = new SongFileService();
    // 表格定义
    const tables = reactive({
      list: [
        {
          title: "曲谱文件管理",
          rowKey: "id",
          columns: [
            {
              title: "ID",
              dataIndex: "id",
              align: "center",
              width: "80px",
            },
            {
              title: "曲谱名称",
              dataIndex: "name",
              align: "center",
              width: "240px",
            },
            {
              title: "第几周",
              dataIndex: "week",
              align: "center",
              width: "120px",
            },
            {
              title: "作者",
              dataIndex: "author",
              align: "center",
              width: "180px",
            },
            {
              title: "速度",
              dataIndex: "tempo",
              align: "center",
              width: "150px",
            },
            {
              title: "是否带和弦",
              dataIndex: "hasChord",
              align: "center",
              width: "120px",
            },
            {
              title: "旋律谱文件",
              dataIndex: "melodyFile",
              align: "center",
              width: "280px",
            },
            {
              title: "和弦谱文件",
              dataIndex: "chordFile",
              align: "center",
              width: "280px",
            },
            {
              title: "排序",
              dataIndex: "sort",
              align: "center",
              width: "120px",
            },
            {
              title: "备注",
              dataIndex: "remark",
              align: "center",
              width: "280px",
            },
            {
              title: "上传时间",
              dataIndex: "createTime",
              align: "center",
              width: "240px",
            },
          ],
          toolbar: {
            left: ["refresh", "add"],
            right: ["filter", "search"],
            add: {
              permissions: "music:songFile:add",
              handler: () => {
                const addPopupRef = tablePageRef.value.getPopup("addRef");
                addPopupRef.value.open({ type: 'add' });
              }
            },
          },
          searchForm: {
            name: {
              type: "input",
              label: "曲谱名称",
              attrs: { placeholder: "曲谱名称", allowClear: true },
            },
            author: {
              type: "input",
              label: "作者",
              attrs: { placeholder: "作者", allowClear: true },
            },
            week: {
              type: "input_number",
              label: "第几周",
              attrs: { placeholder: "第几周", min: 1 },
            },
          },
          service: songFileService,
          operation: ({ record }) => [
            {
              type: "edit",
              permissions: "music:songFile:edit",
              clickHandler: () => {
                const addPopupRef = tablePageRef.value.getPopup("addRef");
                addPopupRef.value.open({ type: 'edit', id: record.id });
              }
            },
            {
              type: "delete",
              permissions: "music:songFile:remove",
              clickHandler: "delete",
            },
          ],
          bodyCell: ({ text, record, index, column }) => {
            if (column.dataIndex === "hasChord") {
              return <>
                <span>{text?.toString?.() === '1' ? "是" : "否"}</span>
              </>
            }
            if (column.dataIndex === "melodyFile") {
              return text ? <div class={styles.fileUrl} onClick={() => { downLoadUrl(text, record) }}>{text}</div> : <span class={styles.noFile}>暂未上传旋律谱文件</span>
            }
            if (column.dataIndex === "chordFile") {
              return text ? <div class={styles.fileUrl} onClick={() => { downLoadUrl(text, record) }}>{text}</div> : <span class={styles.noFile}>暂未上传和弦谱文件</span>
            }
          },
          popups: [
            {
              ref: "addRef",
              dom: () => <Add onChange={() => { tablePageRef.value.reload() }} />,
            },
          ],
          pagination: true,
          tableSourceFormat: {
            data: 'rows',
            pageSize: 'pageSize',
            current: 'pageNum',
          },
        }
      ],
    } as tablesInterface)
    // 下载文件
    const downLoadUrl = async (file_url: string, record: any) => {
      const fileExtension = file_url?.split?.('.')?.pop?.()?.toLowerCase?.() || '';
      const [err, res] = await to(fetch(file_url));
      if (!err) {
        const blob = await res?.blob();
        // 创建一个指向Blob对象的URL
        const url = window.URL.createObjectURL(blob as any);
        // 创建一个隐藏的<a>元素
        const a = document.createElement('a');
        a.style.display = 'none';
        // 设置<a>元素的href属性为Blob对象的URL
        a.href = url;
        // 设置下载的文件名（可选，这里使用URL的最后一部分作为文件名）
        const filename = file_url.split('/').pop();
        a.download = filename || `untitled.${fileExtension}`;
        // 将<a>元素添加到文档中（虽然它是隐藏的）
        document.body.appendChild(a);
        // 触发<a>元素的点击事件以下载文件
        a.click();
        // 释放URL对象（不再需要时）
        window.URL.revokeObjectURL(url);
      }
    }
    // 配置项
    const config = reactive({
      table: tables.list[0],
    })
    return () => (
      <TablePage ref={tablePageRef} config={config} />
    )
  }
})